#!/bin/sh

CODE_HOME=/mnt/admin/code/task
TOMCAT_HOME=/mnt/admin/tomcat-task
PACKAGE_HOME=/mnt/admin/code/task
PACKAGE_COMMAND="mvn clean package -Dmaven.test.skip=true -Ppro"
WAR_NAME=task-1.0-SNAPSHOT.war
APP_PNAME=task
APP_PORT=8083
APP_CHECK_URL="http://task.autogen.cn/index.htm"

echo "update code...."
cd $CODE_HOME
git pull
STATUS=$?
if [ "$STATUS" -ne "0" ]; then
        echo >&2 "git pull failed with $STATUS"
        exit 1
fi


echo "stop server...."
sleep 1

ps aux | grep -v grep | grep "$APP_PNAME" > /dev/null
STATUS=$?
if [ "$STATUS" -eq "0" ]; then
    echo "kill $SERVICE."
    ps ax | grep $APP_PNAME | grep -v grep | awk '{print $1}'| xargs kill
fi


cd ${PACKAGE_HOME}

${PACKAGE_COMMAND}

STATUS=$?
if [ "$STATUS" -eq "0" ]; then
        echo "maven deploy successful"
else
        echo >&2 "Deployment Failed"
        exit 1
fi



mv target/${WAR_NAME} ROOT.war
rm -rf ${TOMCAT_HOME}/webapps/ROOT.war
rm -rf ${TOMCAT_HOME}/webapps/ROOT

cp ROOT.war ${TOMCAT_HOME}/webapps/

echo "start server...."

nohup sh ${TOMCAT_HOME}/bin/startup.sh &

STATUS=$?
if [ "$STATUS" -eq "0" ]; then
        echo "server run successful"
else
        echo >&2 "server run failed"
        exit 1
fi

sleep 1

echo "start check app port $APP_PORT"
i=0
while :
do
  stillRunning=$(netstat -an|grep LISTEN|egrep "${APP_PORT}" |grep -v "grep")
  if [ "$stillRunning" ] ; then
    echo "port bind success.."
    break
  else
    ((i++));
    echo "wait port bind...${i}"
  fi
  sleep 1
done

echo "start check app url $APP_CHECK_URL"

i=0
while :
do
  httpstatus=$(curl -I -m 10 -o /dev/null -s -w %{http_code} "${APP_CHECK_URL}")
  if [ "$httpstatus" -eq "200" ] ; then
    echo "server start success.."
    break
  else
    ((i++));
    echo "wait server start...${i} current return status ${httpstatus}"
  fi
  sleep 1
done